package org.jeecg.modules.filebank.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.utils.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.file.entity.FileBig;
import org.jeecg.modules.file.service.IFileBigService;
import org.jeecg.modules.filebank.entity.CrdFileBli;
import org.jeecg.modules.filebank.entity.CrdFileBliGroup;
import org.jeecg.modules.filebank.entity.CrdFileBliTag;
import org.jeecg.modules.filebank.service.ICrdFileBliGroupService;
import org.jeecg.modules.filebank.service.ICrdFileBliService;
import org.jeecg.modules.filebank.service.ICrdFileBliTagService;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDepartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

//import org.apache.shiro.SecurityUtils;

/**
* @Description: 文件库
* @Author: jeecg-boot
* @Date:   2020-05-15
* @Version: V1.0
*/
@Slf4j
@Api(tags="文件库")
@RestController
@RequestMapping("/filebank/api")
public class CrdFileBliController extends JeecgController<CrdFileBli, ICrdFileBliService> {
    @Autowired
    private ICrdFileBliService crdFileBliService;

    @Autowired
    private ICrdFileBliGroupService crdFileBliGroupService;

    @Autowired
    private ICrdFileBliTagService crdFileBliTagService;

    @Autowired
    ISysDepartService sysDepartService;


    @Autowired
    IFileBigService fileBigService;

    @Value("${bigFile.url}")
    String bigFileUrl;
    @Value("${bigFile.per}")
    String bigFileUrlPer;
   /**
    * 查询一级所有数据
    *
    * @param crdFileBli
    * @param req
    * @return
    */
   @AutoLog(value = "文件库-查询一级所有数据")
   @ApiOperation(value="文件库-查询一级所有数据", notes="文件库-查询一级所有数据")
   @GetMapping(value = "/queryFileBankList")
   public Result<?> queryFileBankList(CrdFileBli crdFileBli,
                              HttpServletRequest req) {
       QueryWrapper<CrdFileBli> crdFileBliQueryWrapper  = new QueryWrapper<>();
       //1、全部可见  2、小组 3、个人可见
       LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
       if(crdFileBli.getShowRange() == 3){
           //查全部
           crdFileBliQueryWrapper.eq("create_by", sysUser.getUsername());
       }else if(crdFileBli.getShowRange() == 2) {
//           crdFileBliQueryWrapper.in("depart_id", sysUser.getDepartIds());
           List<SysDepart> departList = sysDepartService.queryUserDeparts(sysUser.getId());
           for(SysDepart depart: departList ){
               crdFileBliQueryWrapper.like("depart_id", depart.getId());
           }
       }

       crdFileBliQueryWrapper.eq("show_range", crdFileBli.getShowRange());

       crdFileBliQueryWrapper.eq("show_range", crdFileBli.getShowRange());
       crdFileBliQueryWrapper.eq("del_flag","0");
       crdFileBliQueryWrapper.isNull("parent_id").orderByAsc("create_time");

       List<CrdFileBli> list = crdFileBliService.list(crdFileBliQueryWrapper);
       for (CrdFileBli fileBli : list) {
           if(fileBli.getSizeType()==2){
               //和大文件关联起来
               QueryWrapper<FileBig> fileBigQueryWrapper = new QueryWrapper<>();
               fileBigQueryWrapper.eq("file_lib_id",fileBli.getId());
               FileBig one = fileBigService.getOne(fileBigQueryWrapper);
               if(one !=null){
                   fileBli.setBigFileStatus(one.getStatus());
                   if(StringUtils.isEmpty(fileBli.getFileUrl())){
                       if (!StringUtils.isEmpty(one.getUrl())) {
                           fileBli.setFileUrl(one.getUrl().replace(bigFileUrlPer, bigFileUrl));
                       }
                   }
                   if(!StringUtils.isEmpty(one.getImageUrl())){
                       fileBli.setImageUrl(one.getImageUrl().replace(bigFileUrlPer,bigFileUrl));

                   }

               }

           }
       }

       return Result.ok(list);
   }




    @GetMapping(value = "/getBigFIleById")
    public Result<?> getBigFIleById(String id) {
        QueryWrapper<FileBig> fileBigQueryWrapper = new QueryWrapper<>();
        fileBigQueryWrapper.eq("file_lib_id",id);
        FileBig one = fileBigService.getOne(fileBigQueryWrapper);
        if(one != null){
            if(one.getM3u8Url() !=null){
                one.setM3u8Url(one.getM3u8Url().replace(bigFileUrlPer,bigFileUrl));

            }
            if(one.getImageUrl() !=null){
                one.setImageUrl(one.getImageUrl().replace(bigFileUrlPer,bigFileUrl));

            }



        }
        return Result.ok(one);
    }



    /**
     * 查询一级所有数据
     *
     * @param crdFileBli
     * @param req
     * @return
     */
    @AutoLog(value = "文件库-查询一级所有数据")
    @ApiOperation(value="文件库-查询一级所有数据", notes="文件库-查询一级所有数据")
    @GetMapping(value = "/getTreeList")
    public Result<?> getTreeList(CrdFileBli crdFileBli,
                                       HttpServletRequest req) {
        QueryWrapper<CrdFileBli> crdFileBliQueryWrapper  = new QueryWrapper<>();
        List<SysDepart> departList = new ArrayList<>();
        //1、全部可见  2、小组 3、个人可见
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(crdFileBli.getShowRange() == 3){
            //查全部
            crdFileBliQueryWrapper.eq("create_by", sysUser.getUsername());
        }else if(crdFileBli.getShowRange() == 2) {
//           crdFileBliQueryWrapper.in("depart_id", sysUser.getDepartIds());
             departList = sysDepartService.queryUserDeparts(sysUser.getId());
            for(SysDepart depart: departList ){
                crdFileBliQueryWrapper.like("depart_id", depart.getId());
            }
        }
        crdFileBliQueryWrapper.eq("file_type", 1);

        crdFileBliQueryWrapper.eq("show_range", crdFileBli.getShowRange());
        crdFileBliQueryWrapper.eq("del_flag","0");
        crdFileBliQueryWrapper.isNull("parent_id").orderByAsc("create_time");
        List<CrdFileBli> list = crdFileBliService.list(crdFileBliQueryWrapper);
        for (CrdFileBli fileBli : list) {
            QueryWrapper<CrdFileBli> childQUery  = new QueryWrapper<>();

            //1、全部可见  2、小组 3、个人可见
            if(fileBli.getShowRange() == 3){
                //查全部
                childQUery.eq("create_by", sysUser.getUsername());
            }else if(fileBli.getShowRange() == 2) {
//           crdFileBliQueryWrapper.in("depart_id", sysUser.getDepartIds());
                for(SysDepart depart: departList ){
                    childQUery.like("depart_id", depart.getId());
                }
            }
            childQUery.eq("file_type", 1);

            childQUery.eq("show_range", fileBli.getShowRange());
            childQUery.eq("del_flag","0");
            childQUery.eq("parent_id",fileBli.getId()).orderByAsc("create_time");
            List<CrdFileBli> chilList = crdFileBliService.list(childQUery);
            setTree( fileBli, chilList,  sysUser, departList );

        }

        return Result.ok(list);
    }



    public void setTree(CrdFileBli crdFileBli, List<CrdFileBli> list, LoginUser sysUser,List<SysDepart> departList ){
         if(!CollectionUtil.isEmpty(list)){
             crdFileBli.setCrdFileBliList(list);
             for (CrdFileBli fileBli : list) {
                 QueryWrapper<CrdFileBli> lastQuery  = new QueryWrapper<>();
                 //1、全部可见  2、小组 3、个人可见
                 if(fileBli.getShowRange() == 3){
                     //查全部
                     lastQuery.eq("create_by", sysUser.getUsername());
                 }else if(fileBli.getShowRange() == 2) {
                     for(SysDepart depart: departList ){
                         lastQuery.like("depart_id", depart.getId());
                     }
                 }
                 lastQuery.eq("file_type", 1);

                 lastQuery.eq("show_range", fileBli.getShowRange());
                 lastQuery.eq("del_flag","0");
                 lastQuery.eq("parent_id",fileBli.getId()).orderByAsc("create_time");
                 List<CrdFileBli> childList = crdFileBliService.list(lastQuery);
                 setTree( fileBli, childList,sysUser,departList);
             }
         }
    }



    /**
     * 关键词搜索文件
     *
     * @param crdFileBli
     * @param req
     * @return
     */
    @AutoLog(value = "文件库-关键词搜索文件")
    @ApiOperation(value="文件库-关键词搜索文件", notes="文件库-关键词搜索文件")
    @GetMapping(value = "/searchByKeyword")
    public Result<?> searchByKeyword(CrdFileBli crdFileBli,
                                       HttpServletRequest req) {
        QueryWrapper<CrdFileBli> crdFileBliQueryWrapper  = new QueryWrapper<>();
        //1、全部可见  2、小组 3、个人可见
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(!StringUtils.isEmpty(crdFileBli.getStartTime())){
            String create_time  = crdFileBli.getStartTime()+" 00:00:00";
            crdFileBliQueryWrapper.ge("create_time", create_time);
        }
        if(!StringUtils.isEmpty(crdFileBli.getEndTime())){
            String endTime  = crdFileBli.getEndTime()+" 23:59:59";
            crdFileBliQueryWrapper.le("create_time", endTime);
        }

        if(!StringUtils.isEmpty(crdFileBli.getCreateBy())){
            String[] split = crdFileBli.getCreateBy().split(",");
            List<String> creators= Arrays.asList(split);
            crdFileBliQueryWrapper.in("create_by", creators);

        }
        if(crdFileBli.getShowRange() == 3){
            //查全部
            crdFileBliQueryWrapper.eq("create_by", sysUser.getUsername());
        }else if(crdFileBli.getShowRange() == 2) {
//           crdFileBliQueryWrapper.in("depart_id", sysUser.getDepartIds());
            List<SysDepart> departList = sysDepartService.queryUserDeparts(sysUser.getId());
            for(SysDepart depart: departList ){
                crdFileBliQueryWrapper.like("depart_id", depart.getId());
            }
        }
        crdFileBliQueryWrapper.eq("show_range", crdFileBli.getShowRange());
        crdFileBliQueryWrapper.eq("del_flag","0");
//        crdFileBliQueryWrapper.eq("file_type",2);
        if(!StringUtils.isEmpty(crdFileBli.getGroupName())){
            crdFileBliQueryWrapper.eq("group_name",crdFileBli.getGroupName());
        }

        if(!StringUtils.isEmpty(crdFileBli.getSearchKeyword())){
            crdFileBliQueryWrapper.and(wrapper ->wrapper.like("tag", crdFileBli.getSearchKeyword())
                    .or().like("file_name", crdFileBli.getSearchKeyword()));
        }

        if(null !=crdFileBli.getMediaType()){
            crdFileBliQueryWrapper.eq("media_type",crdFileBli.getMediaType());
        }

        if(!StringUtils.isEmpty(crdFileBli.getAuthorId())){
            crdFileBliQueryWrapper.eq("author_id",crdFileBli.getAuthorId());
        }

        if(null != crdFileBli.getTagList() && crdFileBli.getTagList().length >0){
            for(String tag : crdFileBli.getTagList()){
                crdFileBliQueryWrapper.or().like("tag",tag);
            }
        }

        if(!StringUtils.isEmpty(crdFileBli.getParentId())){
            crdFileBliQueryWrapper.eq("parent_id",crdFileBli.getParentId());
        }


        crdFileBliQueryWrapper.orderByAsc("create_time");
        List<CrdFileBli> list = crdFileBliService.list(crdFileBliQueryWrapper);
        for (CrdFileBli fileBli : list) {
            if(fileBli.getSizeType()==2){
                //和大文件关联起来
                QueryWrapper<FileBig> fileBigQueryWrapper = new QueryWrapper<>();
                fileBigQueryWrapper.eq("file_lib_id",fileBli.getId());
                FileBig one = fileBigService.getOne(fileBigQueryWrapper);
                if(one !=null){
                    fileBli.setBigFileStatus(one.getStatus());
                    if(StringUtils.isEmpty(fileBli.getFileUrl())) {
                        if (!StringUtils.isEmpty(one.getUrl())) {
                            fileBli.setFileUrl(one.getUrl().replace(bigFileUrlPer, bigFileUrl));
                        }
                    }

                    if(!StringUtils.isEmpty(one.getImageUrl())){
                        fileBli.setImageUrl(one.getImageUrl().replace(bigFileUrlPer,bigFileUrl));

                    }
                }

            }
        }

        return Result.ok(list);
    }




    /**
     * 获取所有分组
     *
     * @param req
     * @return
     */
    @AutoLog(value = "文件库-获取所有分组")
    @ApiOperation(value="文件库-获取所有分组", notes="文件库-获取所有分组")
    @GetMapping(value = "/queryAllGroup")
    public Result<?> queryAllGroup(
                                     HttpServletRequest req) {
        QueryWrapper<CrdFileBliGroup> groupQueryWrapper = new QueryWrapper<>();
        groupQueryWrapper.orderByAsc("create_time");
        return Result.ok(crdFileBliGroupService.list(groupQueryWrapper));
    }




    /**
     * 获取所有标签
     *
     * @param req
     * @return
     */
    @AutoLog(value = "文件库-获取所有标签")
    @ApiOperation(value="文件库-获取所有标签", notes="文件库-获取所有标签")
    @GetMapping(value = "/queryAllTag")
    public Result<?> queryAllTag(CrdFileBliTag tag,
            HttpServletRequest req) {
        QueryWrapper<CrdFileBliTag> tagQueryWrapper = new QueryWrapper<>();
        tagQueryWrapper.eq("parent_id",tag.getParentId());
        tagQueryWrapper.orderByAsc("create_time");
        return Result.ok(crdFileBliTagService.list(tagQueryWrapper));
    }



    /**
     * 根据parentId查询
     *
     * @param crdFileBli
     * @param req
     * @return
     */
    @AutoLog(value = "文件库-查询一级所有数据")
    @ApiOperation(value="文件库-查询一级所有数据", notes="文件库-查询一级所有数据")
    @GetMapping(value = "/queryFileBankListByParentId")
    public Result<?> queryFileBankListByParentId(CrdFileBli crdFileBli,
                               HttpServletRequest req) {
        QueryWrapper<CrdFileBli> crdFileBliQueryWrapper  = new QueryWrapper<>();
        //1、全部可见  2、小组 3、个人可见
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(crdFileBli.getShowRange() == 3){
            //查全部
            crdFileBliQueryWrapper.eq("create_by", sysUser.getUsername());
        }else if(crdFileBli.getShowRange() == 2) {
            List<SysDepart> departList = sysDepartService.queryUserDeparts(sysUser.getId());
            for(SysDepart depart: departList ){
                crdFileBliQueryWrapper.like("depart_id", depart.getId());
            }
//            crdFileBliQueryWrapper.in("depart_id", sysUser.getDepartIds());
        }
        crdFileBliQueryWrapper.eq("show_range", crdFileBli.getShowRange());
        crdFileBliQueryWrapper.eq("del_flag","0");
        crdFileBliQueryWrapper.eq("parent_id",crdFileBli.getParentId()).orderByAsc("create_time");
        List<CrdFileBli> list = crdFileBliService.list(crdFileBliQueryWrapper);
        for (CrdFileBli fileBli : list) {
            if(fileBli.getSizeType()==2) {
                //和大文件关联起来
                QueryWrapper<FileBig> fileBigQueryWrapper = new QueryWrapper<>();
                fileBigQueryWrapper.eq("file_lib_id", fileBli.getId());
                FileBig one = fileBigService.getOne(fileBigQueryWrapper);
                if (one != null) {
                    fileBli.setBigFileStatus(one.getStatus());
                    if (StringUtils.isEmpty(fileBli.getFileUrl())) {
                        if (!StringUtils.isEmpty(one.getUrl())) {
                            fileBli.setFileUrl(one.getUrl().replace(bigFileUrlPer, bigFileUrl));
                        }
                    }

                    if (!StringUtils.isEmpty(one.getImageUrl())) {
                        fileBli.setImageUrl(one.getImageUrl().replace(bigFileUrlPer, bigFileUrl));

                    }
                }

            }
        }
        return Result.ok(list);
    }

    /**
     * 添加
     *
     * @param crdFileBli
     * @return
     */
    @AutoLog(value = "文件库-添加")
    @ApiOperation(value="文件库-添加", notes="文件库-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody CrdFileBli crdFileBli) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<SysDepart> departList = sysDepartService.queryUserDeparts(sysUser.getId());
        String departIds = "";
        for (SysDepart depart : departList) {
            departIds += (depart.getId() + ",");
        }

        String tag = "";
        //处理标签信息
        if(null != crdFileBli.getTagList() && crdFileBli.getTagList().length>0){
             tag = Arrays.stream(crdFileBli.getTagList())
                    .collect(Collectors.joining(" "));
            crdFileBli.setTag(tag);

//            for(String tagStr :  crdFileBli.getTagList()){
//                CrdFileBliTag tagBean = new CrdFileBliTag();
//                tagBean.setParentId(crdFileBli.getParentId());
//                tagBean.setTagName(tagStr);
//                UpdateWrapper tagUpdate = new UpdateWrapper();
//                tagUpdate.eq("tag_name",tagStr);
//                crdFileBliTagService.saveOrUpdate(tagBean,tagUpdate);
//            }
        }

        List<Map<String,Object>> fileList = crdFileBli.getFileList();
        if(crdFileBli.getFileType() == 2 && fileList != null){
            for(Map<String,Object> tempFile:fileList){
                CrdFileBli tempFileBean =  new CrdFileBli();

                BeanUtils.copyProperties(crdFileBli,tempFileBean);

                tempFileBean.setFileName(tempFile.get("fileName").toString());
                tempFileBean.setFileSize(null == tempFile.get("fileSize")?0:Long.parseLong(tempFile.get("fileSize").toString()));
                tempFileBean.setFileSuffix(tempFile.get("fileSuffix").toString());
                tempFileBean.setFileUrl(tempFile.get("fileUrl").toString());
                tempFileBean.setMediaType(Integer.parseInt(tempFile.get("mediaType").toString()));
                tempFileBean.setFileType(crdFileBli.getFileType());
                tempFileBean.setDepartId(departIds);
                tempFileBean.setTag(tag);
                tempFileBean.setFileGroupType(1);
                crdFileBliService.save(tempFileBean);
            }
        }else{
            if(crdFileBli.getFileName() !=null){
                String[] split = crdFileBli.getFileName().split("\\.");
                if(split.length>1){
                    crdFileBli.setFileSuffix(crdFileBli.getFileName().split("\\.")[1]);

                }
            }
            crdFileBli.setDepartId(departIds);

            //判断同一级目录下不要有重复的文件夹名 wfx 2022-03-29
            QueryWrapper<CrdFileBli> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("file_type",1);
            queryWrapper.eq("file_name",crdFileBli.getFileName());
            queryWrapper.eq("file_group_type",1);
            queryWrapper.eq("del_flag",0);
            if(!StringUtils.isEmpty(crdFileBli.getParentId())){
                queryWrapper.eq("parent_id",crdFileBli.getParentId());
            }
            queryWrapper.last(" limit 1");
            CrdFileBli crd = crdFileBliService.getOne(queryWrapper);
            if(null != crd){
                return  Result.error("该目录下有重名文件夹");
            }
            //判断同一级目录下不要有重复的文件夹名 wfx 2022-03-29
            crdFileBli.setFileGroupType(1);
            crdFileBliService.save(crdFileBli);

        }



        //将分组信息拼接存入
        if(!StringUtils.isEmpty(crdFileBli.getGroupName())){
            CrdFileBliGroup group = new CrdFileBliGroup();
            group.setGroupName(crdFileBli.getGroupName());
            UpdateWrapper groupUpdate = new UpdateWrapper();
            groupUpdate.eq("group_name",crdFileBli.getGroupName());
            crdFileBliGroupService.saveOrUpdate(group,groupUpdate);
        }


        if(crdFileBli.getSizeType()==2){
            //和大文件关联起来
            FileBig fileBig = new FileBig();
            fileBig.setId(crdFileBli.getGuid());
            fileBig.setFileLibId(crdFileBli.getId());
            fileBigService.updateById(fileBig);
        }

        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param crdFileBli
     * @return
     */
    @AutoLog(value = "文件库-编辑")
    @ApiOperation(value="文件库-编辑", notes="文件库-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody CrdFileBli crdFileBli) {
        crdFileBliService.updateById(crdFileBli);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "文件库-通过id删除")
    @ApiOperation(value="文件库-通过id删除", notes="文件库-通过id删除")
    @GetMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name="id",required=true) String id) {
        crdFileBliService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "文件库-批量删除")
    @ApiOperation(value="文件库-批量删除", notes="文件库-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        this.crdFileBliService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "文件库-通过id查询")
    @ApiOperation(value="文件库-通过id查询", notes="文件库-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
        CrdFileBli crdFileBli = crdFileBliService.getById(id);
        return Result.ok(crdFileBli);
    }


    /**
     * 查询分类
     * @return
     */
    @AutoLog(value = "文件库-查询分类")
    @ApiOperation(value="文件库-查询分类", notes="文件库-查询分类")
    @GetMapping(value = "/queryFileGroupAndFolder")
    public Result<?> queryFileGroupAndFolder(CrdFileBli crdFileBli) {

        QueryWrapper<CrdFileBli> crdFileBliQueryWrapper  = new QueryWrapper<>();
        if(crdFileBli.getFileType() == null || crdFileBli.getFileType()!=0){
            crdFileBliQueryWrapper.eq("file_type", 1);
        }
        crdFileBliQueryWrapper.eq("del_flag","0");
        if(!StringUtils.isEmpty(crdFileBli.getParentId())){
            crdFileBliQueryWrapper.eq("parent_id",crdFileBli.getParentId());
        }else{
            crdFileBliQueryWrapper.isNull("parent_id").or().eq("parent_id","");
        }

        crdFileBliQueryWrapper.eq("file_group_type",crdFileBli.getFileGroupType())
                .orderByAsc("create_time");
        List<CrdFileBli> list = crdFileBliService.list(crdFileBliQueryWrapper);
        for (CrdFileBli fileBli : list) {
            QueryWrapper<CrdFileBli> childQUery  = new QueryWrapper<>();
            if(crdFileBli.getFileType() == null || crdFileBli.getFileType()!=0){
                childQUery.eq("file_type", 1);
            }
            childQUery.eq("del_flag","0");
            childQUery.eq("parent_id",fileBli.getId());
            childQUery.eq("file_group_type",crdFileBli.getFileGroupType()).orderByAsc("create_time");

            if(fileBli.getFileType()==3){
                //如果是大文件，查询大文件
                QueryWrapper<FileBig> fileBigQueryWrapper =  new QueryWrapper<>();
                fileBigQueryWrapper.eq("file_lib_id",fileBli.getId()).last(" limit 1");
                FileBig fileBig = fileBigService.getOne(fileBigQueryWrapper);
                if(fileBig.getImageUrl()!=null&& !StringUtils.isEmpty(fileBig.getImageUrl())) {
                    fileBig.setImageUrl(fileBig.getImageUrl().replace(bigFileUrlPer, bigFileUrl));
                    fileBli.setImageUrl(fileBig.getImageUrl());
                }
                fileBli.setBigFileStatus(fileBig.getStatus());
            }

            List<CrdFileBli> chilList = crdFileBliService.list(childQUery);
            setTreeNew( fileBli, chilList,crdFileBli.getFileGroupType(),crdFileBli.getFileType() );
        }

        return Result.ok(list);
    }



    public void setTreeNew(CrdFileBli crdFileBli, List<CrdFileBli> list,int groupType,Integer fileType){
        if(!CollectionUtil.isEmpty(list)){
            crdFileBli.setCrdFileBliList(list);
            for (CrdFileBli fileBli : list) {
                QueryWrapper<CrdFileBli> lastQuery  = new QueryWrapper<>();
                if(fileType == null || fileType!=0){
                    lastQuery.eq("file_type", 1);
                }
                lastQuery.eq("del_flag","0");
                lastQuery.eq("parent_id",fileBli.getId());
                lastQuery.eq("file_group_type",groupType).orderByAsc("create_time");
                if(fileBli.getFileType()==3){
                    //如果是大文件，查询大文件
                    QueryWrapper<FileBig> fileBigQueryWrapper =  new QueryWrapper<>();
                    fileBigQueryWrapper.eq("file_lib_id",fileBli.getId()).last(" limit 1");
                    FileBig fileBig = fileBigService.getOne(fileBigQueryWrapper);
                    if(fileBig.getImageUrl()!=null&& !StringUtils.isEmpty(fileBig.getImageUrl())){
                        fileBig.setImageUrl(fileBig.getImageUrl().replace(bigFileUrlPer,bigFileUrl));
                        fileBli.setImageUrl(fileBig.getImageUrl());
                    }
                    fileBli.setBigFileStatus(fileBig.getStatus());
                }
                List<CrdFileBli> childList = crdFileBliService.list(lastQuery);
                setTreeNew( fileBli, childList,groupType,fileType);
            }
        }
    }


    @AutoLog(value = "文件库-添加文件分类")
    @ApiOperation(value="文件库-添加文件分类", notes="文件库-添加文件分类")
    @PostMapping(value = "/addGroup")
    public Result<?> addGroup(@RequestBody CrdFileBli crdFileBli) {
        QueryWrapper<CrdFileBli> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("file_type",1);
        queryWrapper.eq("file_name",crdFileBli.getFileName());
        queryWrapper.eq("file_group_type",0);
        queryWrapper.eq("del_flag",0);
        if(!StringUtils.isEmpty(crdFileBli.getParentId())){
            queryWrapper.eq("parent_id",crdFileBli.getParentId());
        }
        queryWrapper.last(" limit 1");
        CrdFileBli crd = crdFileBliService.getOne(queryWrapper);
        if(null != crd){
            return  Result.error("该目录下有重名分类");
        }
        crdFileBli.setFileGroupType(0);
        crdFileBli.setFileType(1);
        crdFileBliService.save(crdFileBli);
        return Result.OK("添加成功");
    }



    @AutoLog(value = "文件库-删除文件分类")
    @ApiOperation(value="文件库-删除文件分类", notes="文件库-删除文件分类")
    @PostMapping(value = "/deleteGroup")
    public Result<?> deleteGroup(@RequestBody CrdFileBli crdFileBli) {
       UpdateWrapper<CrdFileBli> updateWrapper = new UpdateWrapper<>();
       updateWrapper.set("del_flag",1);
       updateWrapper.eq("id",crdFileBli.getId());
       crdFileBliService.update(updateWrapper);
        return Result.OK("删除成功");
    }


    @AutoLog(value = "文件库-编辑文件分类")
    @ApiOperation(value="文件库-编辑文件分类", notes="文件库-编辑文件分类")
    @PostMapping(value = "/editGroup")
    public Result<?> editGroup(@RequestBody CrdFileBli crdFileBli) {
        UpdateWrapper<CrdFileBli> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("file_name",crdFileBli.getFileName());
        updateWrapper.eq("id",crdFileBli.getId());
        crdFileBliService.update(updateWrapper);
        return Result.OK("编辑成功");
    }


    @AutoLog(value = "文件库-下载文件夹")
    @ApiOperation(value="文件库-下载文件夹", notes="文件库-下载文件夹")
    @PostMapping(value = "/downloadFolder")
    public Result<?> downloadFolder(@RequestBody CrdFileBli crdFileBli) {
        QueryWrapper<CrdFileBli> queryWrapper = new QueryWrapper<>();
        //查询下级的文件
        queryWrapper.eq("file_type",2);
        queryWrapper.eq("del_flag",0);
        queryWrapper.eq("parent_id",crdFileBli.getId());
        List<CrdFileBli> fileList = crdFileBliService.list(queryWrapper);
        //获取文件夹，递归存入文件
        QueryWrapper<CrdFileBli> queryWrapperfloder = new QueryWrapper<>();
        queryWrapperfloder.eq("file_type",1);
        queryWrapperfloder.eq("del_flag",0);
        queryWrapperfloder.eq("parent_id",crdFileBli.getId());
        List<CrdFileBli> folderList = crdFileBliService.list(queryWrapperfloder);
        setSubFile(folderList,fileList);
        return Result.OK(fileList);
    }

    private void setSubFile(List<CrdFileBli> folderList,List<CrdFileBli> fileList){
        for(CrdFileBli floder:folderList){
            QueryWrapper<CrdFileBli> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("file_type",2);
            queryWrapper.eq("del_flag",0);
            queryWrapper.eq("parent_id",floder.getId());
            List<CrdFileBli> fileListSub = crdFileBliService.list(queryWrapper);
            fileList.addAll(fileListSub);

            QueryWrapper<CrdFileBli> queryWrapperFolder = new QueryWrapper<>();
            queryWrapperFolder.eq("file_type",1);
            queryWrapperFolder.eq("del_flag",0);
            queryWrapperFolder.eq("parent_id",floder.getId());
            List<CrdFileBli> folderListSub = crdFileBliService.list(queryWrapperFolder);
            setSubFile(folderListSub,fileList);

        }
    }





    @AutoLog(value = "文件库-编辑文件夹")
    @ApiOperation(value="文件库-编辑文件夹", notes="文件库-编辑文件夹")
    @PostMapping(value = "/updateFolder")
    public Result<?> updateFolder(@RequestBody CrdFileBli crdFileBli) {
        QueryWrapper<CrdFileBli> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("file_type",crdFileBli.getFileType());
        if(!StringUtils.isEmpty(crdFileBli.getFileName())){
            queryWrapper.eq("file_name",crdFileBli.getFileName());
            if(crdFileBli.getFileType() == 1 ){
                queryWrapper.eq("file_group_type",1);
            }
            if(!StringUtils.isEmpty(crdFileBli.getParentId())){
                queryWrapper.eq("parent_id",crdFileBli.getParentId());
            }
            queryWrapper.last(" limit 1");
            CrdFileBli crd = crdFileBliService.getOne(queryWrapper);
            if(null != crd){
                return  Result.error("该目录下有重名文件或文件夹");
            }
        }


        UpdateWrapper<CrdFileBli> updateWrapper = new UpdateWrapper<>();
        if(!StringUtils.isEmpty(crdFileBli.getFileName())){
            updateWrapper.set("file_name",crdFileBli.getFileName());
        }

        if(!StringUtils.isEmpty(crdFileBli.getAuthorId())){
            updateWrapper.set("author_id",crdFileBli.getAuthorId());
        }
        if(!StringUtils.isEmpty(crdFileBli.getAuthorName())){
            updateWrapper.set("author_name",crdFileBli.getAuthorName());
        }

        if(crdFileBli.getContentTime() != null){
            updateWrapper.set("content_time",crdFileBli.getContentTime());
        }
        if(crdFileBli.getShowRange() != null){
            updateWrapper.set("show_range",crdFileBli.getShowRange());
        }
        if(!StringUtils.isEmpty(crdFileBli.getParentId())){
            updateWrapper.set("parent_id",crdFileBli.getParentId());
        }

        updateWrapper.eq("id",crdFileBli.getId());
        crdFileBliService.update(updateWrapper);
        return Result.OK("修改成功");
    }


    @AutoLog(value = "文件库-新增标签")
    @ApiOperation(value="文件库-新增标签", notes="文件库-新增标签")
    @PostMapping(value = "/addTag")
    public Result<?> addTag(@RequestBody CrdFileBliTag tag) {
        crdFileBliTagService.save(tag);
        return Result.OK("添加标签成功");
    }



    @AutoLog(value = "文件库-删除标签")
    @ApiOperation(value="文件库-删除标签", notes="文件库-删除标签")
    @PostMapping(value = "/deleteTag")
    public Result<?> deleteTag(@RequestBody CrdFileBliTag tag) {
        crdFileBliTagService.removeById(tag.getId());
        return Result.OK("删除标签成功");
    }


    @AutoLog(value = "文件库-编辑标签")
    @ApiOperation(value="文件库-编辑标签", notes="文件库-编辑标签")
    @PostMapping(value = "/editTag")
    public Result<?> editTag(@RequestBody CrdFileBliTag tag) {
        UpdateWrapper<CrdFileBliTag> updateWrapper  = new UpdateWrapper<>();
        if(!StringUtils.isEmpty(tag.getTagName())){
            updateWrapper.set("tag_name",tag.getTagName());
        }

        if(!StringUtils.isEmpty(tag.getParentId())){
            updateWrapper.set("parent_id",tag.getParentId());
        }
        updateWrapper.eq("id",tag.getId());
        crdFileBliTagService.update(updateWrapper);
        return Result.OK("编辑标签成功");
    }

}
